package  
{
  import flash.display.Sprite;
  import mge.graph.Node;
	/**
   * ...
   * @author ivan
   */
  public class DeleteSelectionCommand implements Command
  {
    
    public function DeleteSelectionCommand(graphStage:GraphStage) 
    {
      this.graphStage = graphStage;
      selectedItems = graphStage.selection.items.concat();
        
      redo();
    }
    
    public function undo():void
    {
      for (var i:int = 0; i < selectedItems.length; i++)
        graphStage.addChild(selectedItems[i]);
    }
    
    // No solo borra la seleccion sino que borra tambien las aristas unidas a nodos borrados.
    public function redo():void
    {
      // Guarda los nodos que se estan borrando
      var nodes:Vector.<Node> = new Vector.<Node>();
      for (var i:int = 0; i < selectedItems.length; i++)
      {
        var vn:VisualNode = selectedItems[i] as VisualNode;
        if (vn)
          nodes.push(vn.node);

        graphStage.removeChild(selectedItems[i]); // borra el nodo en si
      }
      
      // Borra aristas pegadas a los nodos encontrados.
      for (i; i < graphStage.numChildren; i++)
      {
        function inEdge(item:Node, index:int, vector:Vector.<Node>):Boolean { return (item.name == ve.edge.source.name || item.name == ve.edge.target.name); }
      
        var ve:VisualEdge = graphStage.getChildAt(i) as VisualEdge;
        if (ve && nodes.some(inEdge, this))
        {
          selectedItems.push(ve);
          graphStage.removeChild(ve);
          i--;
        }
      }
      
      // Limpia la seleccion del stage, pero se acuerda de selectedItems, que puede untilizar para el undo.
      graphStage.selection.items.splice(0, graphStage.selection.items.length);
    }
    
    private var graphStage:GraphStage;
    private var selectedItems:Vector.<Sprite>;
    
  }

}